package com.ck.ck_back.service.impl;

import com.ck.ck_back.dao.CommentMapper;
import com.ck.ck_back.dao.FocusMapper;
import com.ck.ck_back.dao.LikeProductionMapper;
import com.ck.ck_back.dao.ProductionMapper;
import com.ck.ck_back.pojo.Focus;
import com.ck.ck_back.pojo.LikeProduction;
import com.ck.ck_back.pojo.Production;
import com.ck.ck_back.service.productionservice;
import com.ck.ck_back.utils.RedisKeyUtils;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class productionserviceImpl implements productionservice {
    @Resource
    private ProductionMapper productionMapper;
    @Resource
    private CommentMapper commentMapper;
    @Resource
    private LikeProductionMapper likeProductionMapper;
    @Resource
    private FocusMapper focusMapper;
    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    @Override
    public Production select(int production_id) {
        System.out.println(productionMapper.selectByPrimaryKey(production_id));
        return productionMapper.selectByPrimaryKey(production_id);
    }

    @Override
    public List<Production> selectbytype(int type,int state) {
        if (type>=1000 && type<1006 && state>=0 &&state<4) {
            List<Production> productions = productionMapper.selectbytype(type,state);
            for (Production production:productions
                 ) {
                int new_like = likeProductionMapper.getnum(production.getProductionId());
                production.setLikeCount((long)new_like);
                productionMapper.updateByPrimaryKeySelective(production);
            }
            return productions;

        }else {
            return null;
        }
    }

//    查询作者不同状态的作品
    @Override
    public List<Production> selectby_openid_state(String openid, int state) {
        List<Production> productions = productionMapper.selectby_openid_state(openid,state);
        if (productions !=null){
            return productions;
        }else {
            return null;
        }

    }

    //    插入内容,404参数错误，2失败,不然成功
    @Transactional
    @Override
    public int insertSelective(Production production) {
        System.out.println(production);
        if (production.getProductionTitle() != null &&!production.getProductionTitle().equals("")
                && production.getLogoUrl() != null && !production.getLogoUrl().equals("") &&
                production.getContentId() !=null && production.getType() !=null &&
                production.getAuthorId() !=null && !production.getAuthorId().equals("") ){
           int result = productionMapper.insertSelective(production);
            System.out.println(result);
           if (result == 1){
               List<Production> productions = productionMapper.selectByAuthorId(production.getAuthorId());
               System.out.println(productions);
               return productions.get(productions.size()-1).getProductionId();
           }else {return 20000;}
        }else {return 40400;}

    }

//    修改内容,404参数错误,3无此作品，先创建,2更新失败,1成功
//    内容id和文章绑定死，不允许更改,作者同理
    @Override
    @Transactional
    public int update(Production production) {
        if (production.getProductionId() !=null &&
                production.getProductionTitle() != null &&!production.getProductionTitle().equals("")
                && production.getLogoUrl() != null && !production.getLogoUrl().equals("") &&
                production.getContentId() ==null && production.getType() !=null){
            Production production1 = productionMapper.selectByPrimaryKey(production.getProductionId());
            if (production1 != null){
               int result = productionMapper.updateByPrimaryKeySelective(production);
               if (result == 1){
                   return result;
               }else {return 2;}
            }else {return 3;}
        }else {return 404;}
    }
    //    修改文章的状态,404参数错误，3无此作品，2更新失败，1更新成功
    @Transactional
    @Override
    public int update_state(int production_id,int state) {
        if (!String.valueOf(production_id).equals("") && !String.valueOf(state).equals("")){
            Production production = productionMapper.selectByPrimaryKey(production_id);
            if (production != null){
                production.setState(state);
                int result = productionMapper.updateByPrimaryKeySelective(production);
                if (result == 1){
                    return result;
                }else {
                    return 2;
                }
            }else {
                return 3;
            }
        }else {
            return 404;
        }
    }

//    更新点赞数量
    @Override
    public int update_like_count(int production_id, int like_count) {
        return 0;
    }

//    根据作品id返回评论数量
    @Override
    public int select_count_comment(int production_id) {
        if (!String.valueOf(production_id).equals("")){
            int num = commentMapper.select_count_comment(production_id);
            System.out.println(num);
            return num;
        }else {return 404000;}
    }

    @Override
    public int select_collect_user(int production_id) {
        Production production = productionMapper.select_coller_user(production_id);
        return production.getUser_collers().size();
    }

//    根据id拿关注的用户作品
    @Override
    public List<Production> select_focused(String openid) {
        List<Production> productions = new ArrayList<>();
        List<Focus> focusList = focusMapper.selectfoucs(openid);
        for (Focus focus :focusList
             ) {
            String authorid = focus.getPostId();
            List<Production> productionList = productionMapper.selectby_openid_state(authorid,1);
            for (Production pro:productionList
                 ) {
                productions.add(pro);
            }
        }
        productions.sort(Comparator.comparing(Production::getUpdateTime).reversed());
        return productions;
    }

    @Override
    public  List<Production> select_swiper() {
        Long datetime = new Date().getTime()-3*24*60*60*1000;
        List<LikeProduction> likeProductions =likeProductionMapper.selectswiper(datetime);
        Map map_data_sort = new HashMap();
        Map<Integer, List<LikeProduction>> map = likeProductions.stream().collect(Collectors.groupingBy(LikeProduction::getLikedProductionId));
        for (Integer k : map.keySet()) {
            map_data_sort.put(k,map.get(k).size());
        }
//        对map根据value排序
        map_data_sort = sortDescend(map_data_sort);
        List list = new ArrayList();
        int id = 1;
        for (Object k:map_data_sort.keySet()){
            if (id<=5){
//               取前五的id放入list备用
                list.add(k);
                ++id;
            }
        }
        List<Production> productions = new ArrayList<Production>();
        for (Object l:list
             ) {
            Production production = productionMapper.selectByPrimaryKey((Integer) l);
            productions.add(production);
        }

        return productions;
    }

    @Override
    public List<Production> getaudit() {
        return productionMapper.getallwaitaudit();
    }

    // Map的value值降序排序
    public static <K, V extends Comparable<? super V>> Map<K, V> sortDescend(Map<K, V> map) {
        List<Map.Entry<K, V>> list = new ArrayList<>(map.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
            @Override
            public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
                int compare = (o1.getValue()).compareTo(o2.getValue());
                return -compare;
            }
        });

        Map<K, V> returnMap = new LinkedHashMap<K, V>();
        for (Map.Entry<K, V> entry : list) {
            returnMap.put(entry.getKey(), entry.getValue());
        }
        return returnMap;
    }



    //    单纯的返回对象
    public List<LikeProduction> getLikedProductionDataFromRedis() {
        Cursor<Map.Entry<Object, Object>> cursor = redisTemplate.opsForHash().scan(RedisKeyUtils.MAP_KEY_Production_LIKED, ScanOptions.NONE);
        List<LikeProduction> list = new ArrayList<>();
        while (cursor.hasNext()){
            Map.Entry<Object,Object> entry = cursor.next();
            String key = (String) entry.getKey();
            String[] split = key.split("::");
            int likedProductionId = Integer.parseInt(split[0]);
            String likedPostId = split[1];

            String value = (String) entry.getValue();
            String[] splitt = value.split("::");
            Integer state = Integer.parseInt(splitt[0]);
            Long updateTime = Long.valueOf(splitt[1]);

            //组装成 UserLike 对象
            LikeProduction likeProduction = new LikeProduction();
            likeProduction.setLikedProductionId(likedProductionId);
            likeProduction.setLikedPostId(likedPostId);
            likeProduction.setState(state);
            likeProduction.setUpdateTime(updateTime);
            list.add(likeProduction);
        }
        return list;
    }

}
